import 'package:flutter/material.dart';

class MonthSelectionScreen extends StatefulWidget {
  final DateTime? selectedDate;
  final Function(DateTime) onDateSelected;

  const MonthSelectionScreen({
    super.key,
    this.selectedDate,
    required this.onDateSelected,
  });

  @override
  State<MonthSelectionScreen> createState() => _MonthSelectionScreenState();
}

class _MonthSelectionScreenState extends State<MonthSelectionScreen> {
  late DateTime _currentDate;
  final int _yearsRange = 5; 

  final List<String> _monthNames = [
    '1月', '2月', '3月', '4月', '5月', '6月',
    '7月', '8月', '9月', '10月', '11月', '12月'
  ];

  @override
  void initState() {
    super.initState();
    _currentDate = widget.selectedDate ?? DateTime.now();
  }

  
  List<int> _generateYears() {
    final int currentYear = DateTime.now().year;
    final List<int> years = [];
    for (int i = currentYear - _yearsRange; i <= currentYear + _yearsRange; i++) {
      years.add(i);
    }
    return years;
  }

  
  void _onYearSelected(int year) {
    setState(() {
      _currentDate = DateTime(year, _currentDate.month, 1);
    });
  }

  
  void _onMonthSelected(int month) {
    setState(() {
      _currentDate = DateTime(_currentDate.year, month, 1);
    });
  }

  
  void _confirmSelection() {
    widget.onDateSelected(_currentDate);
    Navigator.pop(context);
  }

  
  void _goToToday() {
    setState(() {
      _currentDate = DateTime.now();
    });
  }

  @override
  Widget build(BuildContext context) {
    final List<int> years = _generateYears();

    return Scaffold(
      appBar: AppBar(
        title: const Text('选择月份'),
        leading: IconButton(
          icon: const Icon(Icons.close),
          onPressed: () => Navigator.pop(context),
        ),
        actions: [
          TextButton(
            onPressed: _confirmSelection,
            child: const Text('确定'),
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            
            Container(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: years.map((year) {
                    final bool isSelected = year == _currentDate.year;
                    return Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 8.0),
                      child: InkWell(
                        onTap: () => _onYearSelected(year),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                          decoration: BoxDecoration(
                            color: isSelected ? Colors.pink : Colors.transparent,
                            borderRadius: BorderRadius.circular(16.0),
                          ),
                          child: Text(
                            '$year年',
                            style: TextStyle(
                              color: isSelected ? Colors.white : Colors.black,
                              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                            ),
                          ),
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ),
            ),

            
            Expanded(
              child: GridView.builder(
                padding: const EdgeInsets.all(16.0),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 4,
                  mainAxisSpacing: 16.0,
                  crossAxisSpacing: 16.0,
                  childAspectRatio: 2.5,
                ),
                itemCount: _monthNames.length,
                itemBuilder: (context, index) {
                  final int month = index + 1;
                  final bool isSelected = month == _currentDate.month &&
                      _currentDate.year == DateTime.now().year;
                  final bool isCurrentMonth = month == DateTime.now().month &&
                      _currentDate.year == DateTime.now().year;

                  return InkWell(
                    onTap: () => _onMonthSelected(month),
                    child: Container(
                      decoration: BoxDecoration(
                        color: isSelected ? Colors.pink : Colors.grey[100],
                        borderRadius: BorderRadius.circular(8.0),
                        border: isCurrentMonth
                            ? Border.all(color: Colors.pink, width: 2.0)
                            : null,
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        _monthNames[index],
                        style: TextStyle(
                          color: isSelected ? Colors.white : Colors.black,
                          fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),

            
            Container(
              padding: const EdgeInsets.all(16.0),
              child: ElevatedButton(
                onPressed: _goToToday,
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.pink,
                  minimumSize: const Size(double.infinity, 48.0),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(24.0),
                  ),
                ),
                child: const Text(
                  '回到今天',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}